package com.littlebee.storysuper.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.littlebee.storysuper.R;
import com.littlebee.storysuper.adapter.CircleStoryAdapter;
import com.littlebee.storysuper.entry.BabyStoryPlanEntry;
import com.littlebee.storysuper.entry.BabyStorySeriesEntry;
import com.littlebee.storysuper.entry.MyStoryEntry;
import com.littlebee.storysuper.entry.StoryBabyWantEntry;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.Constant;
import com.littlebee.storysuper.utils.DateUtils;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.littlebee.storysuper.widget.RoundAngleImageView;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;
import com.zss.library.widget.CommonWhiteDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 今日故事
 */
public class TodayStoryActivity extends BaseActivity implements View.OnClickListener {

    private ListView mListView;
    private CircleStoryAdapter adapter;

    List<BabyStorySeriesEntry> names = new ArrayList<BabyStorySeriesEntry>();
    MyStoryEntry myStoryEntry;
    StoryBabyWantEntry storyBabyWantEntry;
    RoundAngleImageView photo1, photo2;
    TextView title1, title2,title1_1, title2_1;
    TextView des1, des2,tv1,tv2;
    LinearLayout ly_1, ly_2;
    private ImageView photo2_right1;
    String playerUrl = "";
    View view;
    private GridView gv;
    CommonAdapter<BabyStoryPlanEntry> mAdapter;
    List<BabyStoryPlanEntry> babyStoryPlanEntryNames = new ArrayList<BabyStoryPlanEntry>();
    SharedPreferences sharedPreferences;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_today_story;
    }

    @Override
    public void initView() {
        super.initView();
        sharedPreferences = getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据

        mListView = (ListView) findViewById(R.id.listview);
        view=getLayoutInflater(R.layout.activity_today_story_top);
        photo1 = (RoundAngleImageView) view.findViewById(R.id.photo1);
        photo2 = (RoundAngleImageView) view.findViewById(R.id.photo2);
        title1 = (TextView) view.findViewById(R.id.title1);
        title2 = (TextView) view.findViewById(R.id.title2);
        title1_1 = (TextView) view.findViewById(R.id.title1_1);
        title2_1 = (TextView) view.findViewById(R.id.title2_1);
        tv1 = (TextView) view.findViewById(R.id.tv1);
        tv2 = (TextView) view.findViewById(R.id.tv2);
        des1 = (TextView) view.findViewById(R.id.des1);
        des2 = (TextView) view.findViewById(R.id.des2);
        ly_1 = (LinearLayout) view.findViewById(R.id.ly_1);
        ly_2 = (LinearLayout) view.findViewById(R.id.ly_2);
        photo2_right1 = (ImageView) view.findViewById(R.id.photo2_right1);
        photo2_right1.setOnClickListener(this);
        gv=(GridView)view.findViewById(R.id.gv);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        loadData();
        bobyLoadData();
        getBabyHotStoryPlan();
        getBabyStoryPlan();
        mAdapter = new CommonAdapter<BabyStoryPlanEntry>(getActivity(), R.layout.layout_item_story) {
            @Override
            protected void convert(ViewHolder viewHolder, final BabyStoryPlanEntry workerListEntry, int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                TextView name1 = viewHolder.findViewById(R.id.tv1);

                RoundAngleImageView iv = viewHolder.findViewById(R.id.photo);

                name.setText(workerListEntry.getStoryname());
                name1.setVisibility(View.GONE);
                // TODO: 2017/8/15
                Glide.with(TodayStoryActivity.this).load(workerListEntry.getStoryminiphoto()).error(R.mipmap.logo_img).into(iv);


            }
        };
        gv.setAdapter(mAdapter);
        mAdapter.addAll(babyStoryPlanEntryNames);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(TodayStoryActivity.this, StoryInfoActivity.class);
                intent.putExtra("isInfo", false);

                intent.putExtra("info", babyStoryPlanEntryNames.get(position));
                intent.putExtra("isPlan",true);
                startActivity(intent);
            }
        });
        photo1.setOnClickListener(this);
        photo2.setOnClickListener(this);

    }

    private void initToast() {
        if(sharedPreferences.getBoolean("is_Toast",false)==false) {
            final CommonWhiteDialog dialog = new CommonWhiteDialog(this);
            dialog.setTitle("提 醒");
//                        View view1=getLayoutInflater(R.layout.layout_item_dialog);
//                        dialog.setMiddleView(view1);
            dialog.setContentText("点击宝宝选择故事栏的声音图标\n收听宝宝发送的语音");
            dialog.setDisplayMiddleEnable(true);
            dialog.setOnClickCancelListener("确 定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setOnClickConfirmListener("不再提醒", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sharedPreferences.edit().putBoolean("is_Toast", true).commit();
                    dialog.dismiss();

                }
            });
            dialog.show();
        }
    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.today_style_txt));

    }

    /*
   * 今日推荐故事
   *
   * */
    public void loadData() {
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
        NetWorkUtils.post(getActivity(), "gettodaystoryplan", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                String res = resObj.optString("response")/**.optString("storypages")*/;
                myStoryEntry = GsonUtils.getObjFromJSON(res, MyStoryEntry.class);
                if (myStoryEntry != null) {
                    Glide.with(TodayStoryActivity.this).load(myStoryEntry.getStorypages().get(0).getPageurl()).error(R.mipmap.logo_img).into(photo1);
                    title1.setText(myStoryEntry.getStoryname());
                    title1_1.setText(myStoryEntry.getStorydescription());
                    tv1.setText(DateUtils.getTimeString(Long.parseLong(myStoryEntry.getStoryduration())*1000));

                    des1.setText(getString(R.string.today_tuijian_story_txt));

                }

            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);


            }
        });
    }

    /*
 * 宝宝想听故事
 *
 * */
    public void bobyLoadData() {
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
        NetWorkUtils.post(getActivity(), "getlaststorybabywant", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                // TODO: 2017/9/4
                String res = resObj.optString("response");
                storyBabyWantEntry = GsonUtils.getObjFromJSON(res, StoryBabyWantEntry.class);
                playerUrl = storyBabyWantEntry.getBabywantaudiomsg();
                if (TextUtils.isEmpty(playerUrl)) {
                    photo2_right1.setVisibility(View.GONE);
                }
                if (storyBabyWantEntry.getWantstoryinfo() != null
                        && storyBabyWantEntry.getWantstoryinfo().getStorypages() != null
                        && storyBabyWantEntry.getWantstoryinfo().getStorypages().size() > 0) {
                    Glide.with(TodayStoryActivity.this)
                            .load(storyBabyWantEntry.getWantstoryinfo().getStorypages().get(0).getPageurl())
                            .error(R.mipmap.logo_img)
                            .into(photo2);
                    title2.setText(storyBabyWantEntry.getWantstoryinfo().getStoryname());
                    title2_1.setText(storyBabyWantEntry.getWantstoryinfo().getStorydescription());
                    tv2.setText(DateUtils.getTimeString(Long.parseLong(storyBabyWantEntry.getWantstoryinfo().getStoryduration())*1000));
                    des2.setText(getString(R.string.boby_like_txt));
                    initToast();

                }
                ly_2.setVisibility(View.VISIBLE);

            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);
            }
        });
    }

    /*
  * 拉取故事计划
  *
  * */
    public void getBabyStoryPlan() {
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
//        long times = System.currentTimeMillis();
//        hashMap.put("startdate", DateUtils.getTimeDay1(times));
//        hashMap.put("enddate", DateUtils.getTimeDay1(times/**+((long)2*24*60*60*1000)*/));

        NetWorkUtils.post(getActivity(), "getbabystoryseries", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                //LogUtils.i("XHX", "XHXSUCC:" + result);
                String res = resObj.optString("response")/**.optString("storypages")*/;

                names = GsonUtils.getListFromJSON(res, BabyStorySeriesEntry.class);
//                LogUtils.i("XHX", "XHXSIZE:" + names.size());
//                mAdapter.replaceAll(names);
                if (adapter == null) {
                    adapter = new CircleStoryAdapter(names, TodayStoryActivity.this);
                    mListView.setAdapter(adapter);
                } else {
                    adapter.notifyDataSetChanged();
                }
                mListView.addHeaderView(view);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);


            }
        });
    }
    /*
      * 拉取故事计划
      *
      * */
    public void getBabyHotStoryPlan() {
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();
        hashMap.put("phoneId", user.getMobile());
        long times = System.currentTimeMillis();
        hashMap.put("startdate", DateUtils.getTimeDay1(times));
        hashMap.put("enddate", DateUtils.getTimeDay1(times/**+((long)2*24*60*60*1000)*/));

        NetWorkUtils.post(getActivity(), "getbabystoryplan", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                //LogUtils.i("XHX", "XHXSUCC:" + result);
                String res = resObj.optString("response")/**.optString("storypages")*/;

                babyStoryPlanEntryNames = GsonUtils.getListFromJSON(res, BabyStoryPlanEntry.class);
//                LogUtils.i("XHX", "XHXSIZE:" + names.size());
                mAdapter.replaceAll(babyStoryPlanEntryNames);

            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);


            }
        });
    }
    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.photo1:
                intent = new Intent(TodayStoryActivity.this, StoryInfoActivity.class);
                intent.putExtra("isInfo", true);
                intent.putExtra("info", myStoryEntry);
                startActivity(intent);
                break;
            case R.id.photo2:
                intent = new Intent(TodayStoryActivity.this, StoryInfoActivity.class);
                intent.putExtra("isInfo", true);
                intent.putExtra("info", storyBabyWantEntry.getWantstoryinfo());
                startActivity(intent);
                break;
            case R.id.photo2_right1:
                if (TextUtils.isEmpty(playerUrl)) {
                    ToastUtil.displayShortToast("没有可播放的语音哦");
                    return;
                }
                startPlayer(playerUrl);
                break;
        }
    }

    private MediaPlayer mPlayer = null;

    private void startPlayer(String item) {
        mPlayer = new MediaPlayer();
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaRelease();
                return true;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaRelease();

            }
        });
        try {
            mPlayer.setDataSource(item);
            final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(false);
                mPlayer.prepare();
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mediaRelease() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    @Override
    protected void onDestroy() {
        mediaRelease();
        super.onDestroy();
    }
}
